﻿using System;
using System.Globalization;
using System.Threading;
using Rhino.Security;
using RhinoSecurity = Rhino.Security;

namespace Tanmia.Basis.Security.Adapter
{
    public class AuthorizationService : IAuthorizationService
    {
        private RhinoSecurity.Interfaces.IAuthorizationService rhinoAuthSrv;
        private IAuthenticationService authenticationService;

        public AuthorizationService(RhinoSecurity.Interfaces.IAuthorizationService rhinoAuthSrv, IAuthenticationService authenticationService)
        {
            this.rhinoAuthSrv = rhinoAuthSrv;
            this.authenticationService = authenticationService;
        }

        #region IAuthorizationService Members

        public bool IsAuthorize(ApplicationUserInfo user, string operation)
        {
            if (string.IsNullOrEmpty(operation))
                throw new ArgumentNullException("operation");

            if (user == null)
                throw new ArgumentNullException("user");

            IUser rhinoUser = this.TryCast<IUser>(user);
            return rhinoAuthSrv.IsAllowed(rhinoUser, operation);
        }

        public bool IsAuthorize(string operation)
        {
            if (string.IsNullOrEmpty(operation))
                throw new ArgumentNullException("operation");

            return IsAuthorize(authenticationService.User , operation);
        }

        public void Authorize(string operation)
        {
            if (string.IsNullOrEmpty(operation))
                throw new ArgumentNullException("operation");

            if (!IsAuthorize(operation))
                throw new AccessDeniedSecurityException(string.Format(CultureInfo.CurrentCulture, "{0} is denied for {1} user.", operation, Thread.CurrentPrincipal.Identity.Name));
        }

        #endregion
    }
}
